<?php
/**
 * Add a new User in the system
 */

use Fox\Html\Screen;

$xview = Xview::instance();
if (!Fox\Authorization\Manager::check('Users-Create'))
{
	$xview->accessDenied();
}

$screen = new Screen('eUser','create');
// Header
$block = Xview::instance()->component("users","headInfo");
$screen->add($block);
// Preferences
$blpref = Xview::instance()->component("users","preferences");
$screen->add($blpref);
// Custom
$blAdd = Xview::instance()->component("users","customDataInfo");
if(!empty($blAdd))
$screen->add($blAdd);

if($screen->submitted())
{
	$inputs = $screen->get();
	if(!$screen->errors())
	{
		// Check Duplicates
		$email = $inputs['email'];
		$finder = new User();
		$res = $finder->find(new Fox\Dao\SqlFragment("LOWER(email) = LOWER(?)",array($email)));
		if (count($res) > 0)
		{
			Fox\Message::Error(Msg(User::BUNDLE_NAME,3,$email));
		}
	}
	if(!$screen->errors())
	{
		try {
			$inputs['passw'] = md5("initial");
			
			$user = new User();
			$user->setFields($inputs);
			$user->create();
			$user->updateWebApps($xview->id(),$inputs['proid']);
			// Set Prefs
			foreach($blAdd->items() as $item)
			{
				$user->SetPrefs($item->id(), $inputs[$item->id()]);
			}
			$user->SetPrefs("op_entity", $inputs['op_entity']);
			// Attach the current application to the user
			Fox\Message::Success(Msg(Fox\Msg::BUNDLE,Fox\Msg::MSG_CREATE,$user->email));
			$xview->redirect('?mod=users&execute=true');
		}
		catch (Fox\Object\Exception\Save $e)
		{
			Fox\Core\Errors::pushMessage($e);
		}
	}
}
echo $screen->Display();